import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { voteForDrawing, checkUserVote, getDrawingVotes } from '../utils/voteApi';
import type { DrawingType } from '../types/drawing';

interface VotableDrawingProps {
  id: number;
  dataUrl: string;
  type: DrawingType;
  username: string;
  x: number;
  y: number;
}

// 本地缓存投票状态，避免频繁API调用
const voteCache = new Map<string, { hasVoted: boolean, timestamp: number }>();
const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

const VotableDrawing: React.FC<VotableDrawingProps> = ({ id, dataUrl, username, x, y }) => {
  const [showInfo, setShowInfo] = useState(false);
  const [voteCount, setVoteCount] = useState(0);
  const [hasVoted, setHasVoted] = useState(false);
  const [isVoting, setIsVoting] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const { isAuthenticated, user } = useAuth();

  useEffect(() => {
    // 获取投票数
    const fetchVoteCount = async () => {
      try {
        const count = await getDrawingVotes(id);
        setVoteCount(count);
      } catch (error) {
        console.error('Error fetching vote count:', error);
      }
    };

    // 检查用户是否已投票（带缓存优化）
    const checkVoteStatus = async (forceRefresh = false) => {
      if (isAuthenticated && user) {
        const cacheKey = `${user.id}-${id}`;
        const cached = voteCache.get(cacheKey);
        const now = Date.now();
        
        // 如果有有效缓存且不强制刷新，直接使用缓存
        if (!forceRefresh && cached && (now - cached.timestamp) < CACHE_DURATION) {
          setHasVoted(cached.hasVoted);
          return;
        }
        
        try {
          const voted = await checkUserVote(user.id, id);
          const hasVotedResult = !!voted;
          setHasVoted(hasVotedResult);
          
          // 更新缓存
          voteCache.set(cacheKey, {
            hasVoted: hasVotedResult,
            timestamp: now
          });
        } catch (error) {
          console.error('Error checking vote status:', error);
        }
      } else {
        setHasVoted(false);
      }
    };

    fetchVoteCount();
    checkVoteStatus();

    // 设置定时刷新投票数据（每30秒刷新一次）
    const refreshInterval = setInterval(() => {
      fetchVoteCount();
      if (isAuthenticated && user) {
        checkVoteStatus(true); // 定时刷新时强制更新缓存
      }
    }, 30000);

    return () => {
      clearInterval(refreshInterval);
    };
  }, [id, isAuthenticated, user]);

  const handleVote = async (e: React.MouseEvent) => {
    e.stopPropagation();

    if (isVoting) {
      // 防止快速连点导致重复提交
      return;
    }
    
    if (!isAuthenticated || !user) {
      setErrorMessage('请先登录后再投票');
      setTimeout(() => setErrorMessage(''), 3000);
      return;
    }

    if (hasVoted) {
      setErrorMessage('您已经为这个作品投过票了');
      setTimeout(() => setErrorMessage(''), 3000);
      return;
    }

    try {
      setIsVoting(true);
      setErrorMessage('');
      await voteForDrawing(user.id, id);
      setHasVoted(true);
      
      // 更新本地缓存
      const cacheKey = `${user.id}-${id}`;
      voteCache.set(cacheKey, {
        hasVoted: true,
        timestamp: Date.now()
      });
      
      // 显示成功提示
      setShowSuccess(true);
      setTimeout(() => setShowSuccess(false), 2000);
      
      // 重新从后端拉取票数，避免本地+1与实际不一致
      const count = await getDrawingVotes(id);
      setVoteCount(count);
    } catch (error: any) {
      console.error('Error voting:', error);
      const message = error.message || '投票失败，请重试';
      setErrorMessage(message);
      setTimeout(() => setErrorMessage(''), 3000);
    } finally {
      setIsVoting(false);
    }
  };

  return (
    <g 
      transform={`translate(${x - 40}, ${y - 40})`} 
      className="cursor-pointer transition-opacity hover:opacity-100"
      style={{ opacity: 0.8 }}
      onClick={() => setShowInfo(!showInfo)}
    >
      <image 
        href={dataUrl} 
        x="0" 
        y="0" 
        width="80" 
        height="80" 
        style={{ 
          transformOrigin: 'center', 
          animation: 'bob 4s ease-in-out infinite',
          animationDelay: `${Math.random() * 2}s`,
          borderRadius: '8px'
        }} 
      />
      
      {showInfo && (
        <foreignObject x="-60" y="-80" width="200" height="100">
          <div className="bg-base-100 rounded-lg p-2 shadow-lg border border-primary relative">
            <p className="text-sm font-medium">{username || '匿名用户'}</p>
            <div className="flex items-center justify-between mt-1">
              <div className="flex items-center">
                <svg className="w-4 h-4 text-yellow-500 mr-1" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.5 8.819c-.783-.57-.38-1.81.588-1.81h3.462a1 1 0 00.95-.69l1.07-3.292z" />
                </svg>
                <span className="text-sm">{voteCount} 票</span>
              </div>
              <button 
                className={`btn btn-xs transition-all duration-200 ${
                  hasVoted 
                    ? 'btn-success' 
                    : isVoting 
                    ? 'btn-disabled loading' 
                    : 'btn-primary hover:btn-primary-focus'
                }`}
                onClick={handleVote}
                disabled={hasVoted || isVoting}
              >
                {isVoting ? (
                  <span className="loading loading-spinner loading-xs"></span>
                ) : hasVoted ? (
                  <>
                    <svg className="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                    已投票
                  </>
                ) : (
                  '投票'
                )}
              </button>
            </div>
            
            {/* 成功提示 */}
            {showSuccess && (
              <div className="absolute -top-8 left-1/2 transform -translate-x-1/2 bg-success text-success-content px-2 py-1 rounded text-xs whitespace-nowrap animate-bounce">
                投票成功！
              </div>
            )}
            
            {/* 错误提示 */}
            {errorMessage && (
              <div className="mt-1 text-xs text-error break-words">
                {errorMessage}
              </div>
            )}
          </div>
        </foreignObject>
      )}
    </g>
  );
};

export default VotableDrawing;